using System;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
using Sirenix.OdinInspector;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Networking;

namespace WorkFlow.Net.Process
{
    [RequireComponent(typeof(AccountInfo))]
    public class NetTreasureChestList : MonoBehaviour
    {
        private static bool _isInit;
        public static bool Initialized => _isInit;
        
        [SerializeField] private UnityEvent onInitialized = new UnityEvent();
        [SerializeField] private UnityEvent<string,System.Action> onNetError = new UnityEvent<string,System.Action>();
        
        public UnityEvent OnInitializedEvent => onInitialized;
        public  UnityEvent<string,System.Action> OnNetError => onNetError;
        
        public static event System.Action OnInitialized;
        public static event System.Action OnInitializedActionOnce;
        
        
        static NetTreasureChestList _instance;
        [ShowInInspector][ReadOnly]
        private TreasureChestInfo[] treasureChestInfoArray;
        void Awake()
        {
            _isInit = false;
            _instance = this;
            AccountInfo accountInfo = GetComponent<AccountInfo>();
            accountInfo.OnLoginSet.AddListener(StartLoadTreasureChestInfoList); 
        }

        private void StartLoadTreasureChestInfoList()
        {
            EnumeratorRunner.Instance.Run(GetUrl(NetPlayerPresData.Instance.TreasureChestListUrl,
                NetPlayerPresData.Instance.Token));
        }
        
        private IEnumerator GetUrl(string url, string token)
        {
            string urlStr = $"{url}";
            Debug.Log("Get URL : " + urlStr + "Token " + token);
            UnityWebRequest request = new UnityWebRequest(urlStr, UnityWebRequest.kHttpVerbGET);
            try
            {
                request.downloadHandler = new DownloadHandlerBuffer();
                request.SetRequestHeader("xy-token", token);
                request.SetRequestHeader("Xysource", "CLIENT");
                request.SetRequestHeader("xy-source", "CLIENT");
                yield return request.SendWebRequest();
                if (request.result == UnityWebRequest.Result.Success)
                {
                    Debug.Log("Response: " + request.downloadHandler.text);
                    GetNetResponse netResponse = JsonConvert.DeserializeObject<GetNetResponse>(request.downloadHandler.text);
                    OnUpdateTreasureChestInfoList(netResponse.Data);
                }
                else
                {
                    Debug.LogError("Error: " + request.error);
                    _instance.onNetError?.Invoke("网络错误[NPP-G]", () =>
                    {
                        EnumeratorRunner.Instance.Run(GetUrl(url, token));
                    });
                }
            }
            finally
            {
                request.Dispose();
            }
        }

        private void OnUpdateTreasureChestInfoList(TreasureChestInfo[] data)
        {
            treasureChestInfoArray = data;
            _isInit = true;
            OnInitialized?.Invoke();
            var temp = OnInitializedActionOnce;
            OnInitializedActionOnce = null;
            temp?.Invoke();
        }

        public static int Count
        {
            get
            {
                if(_instance!=null && Initialized)
                    return _instance.treasureChestInfoArray.Length;
                return 0;
            }
        }

        public static bool CheckTreasureChestInfo(string treasureChestName, out TreasureChestInfo treasureChestInfo)
        {
            if (_instance != null && Initialized )
            {
                List<TreasureChestInfo> treasureChestInfoList = new List<TreasureChestInfo>();
                for (var index = 0; index < _instance.treasureChestInfoArray.Length; index++)
                {
                    var item = _instance.treasureChestInfoArray[index];
                    if (item.ToolName.Equals(treasureChestName))
                    {
                        treasureChestInfo = item;
                        return true;
                    }
                }
            }

            treasureChestInfo = default;
            return false;
        }

        public static bool CheckTreasureChestInfo(string treasureChestName, out TreasureChestInfo[] treasureChestInfo)
        {
            if (_instance != null && Initialized)
            {
                List<TreasureChestInfo> treasureChestInfoList = new List<TreasureChestInfo>();
                for (var index = 0; index < _instance.treasureChestInfoArray.Length; index++)
                {
                    var item = _instance.treasureChestInfoArray[index];
                    if (item.ToolName.Equals(treasureChestName))
                    {
                        treasureChestInfoList.Add(item);
                    }
                }
                treasureChestInfo = treasureChestInfoList.ToArray();
                return treasureChestInfoList.Count > 0;
            }
            treasureChestInfo = null;
            return false;
        }

        public delegate bool CheckCallBack(ref TreasureChestInfo treasureChestInfo);
        public static TreasureChestInfo[] CheckTreasureChestInfo(CheckCallBack  callback)
        {
            if (_instance != null && Initialized && callback != null)
            {
                List<TreasureChestInfo> treasureChestInfoList = new List<TreasureChestInfo>();
                for (var index = 0; index < _instance.treasureChestInfoArray.Length; index++)
                {
                    var item = _instance.treasureChestInfoArray[index];
                    if (callback.Invoke(ref item))
                    {
                        treasureChestInfoList.Add(item);
                    }
                }
                return treasureChestInfoList.ToArray();
            }
            return null;
        }

        private void OnDestroy()
        {
            _instance = null;
            
        }

        private class GetNetResponse
        {
            [JsonProperty("msg")] public string Msg { get; set; }
            [JsonProperty("code")] public int Code { get; set; }
            [JsonProperty("data")] public TreasureChestInfo[] Data { get; set; }
        }
        [System.Serializable]
        public struct TreasureChestInfo
        {
            /// <summary>
            /// TreasureChest ID
            /// </summary>
            [JsonProperty("id")] public string Id;

            /// <summary>
            /// 工具/游戏名（中文）
            /// </summary>
            [JsonProperty("gameName")] public string ToolName;
            /// <summary>
            /// 工具/游戏图标
            /// </summary>
            [JsonProperty("gameCover")] public string GameIcon;
            /// <summary>
            /// 工具/游戏 大类别
            /// </summary>
            [JsonProperty("gameClass1")] public string Category;

            [JsonProperty("gameAddress")] public string Routing;
        }
        /*
         * "createBy": "0",
           "createTime": "2024-12-31 19:09:53",
           "updateBy": "3",
           "updateTime": "2025-07-23 18:51:40",
           "delFlag": 0,
           "remark": "",
           "id": "529375660611731457",
           "gameCover": "https://oss-xingyun-platform.xypsy.com//886/2024/12/31/3331fac2a8954def99401641d269b6a5.jpg",
           "gameName": "缓解学习疲惫",
           "gameClass1": "少儿专区",
           "gameClass2": "热门工具",
           "gameTag": "MEDITATE",
           "gameTagColor": "#A4DA77",
           "gameAddress": "/games/unityTools/?gameName=meditation&gameTag=MEDITATE&abKey=06&toolName=缓解学习疲惫&platform=1",
           "gameDescription": "八分钟，清除疲惫感，重启专注与轻松，重新进入学习状态。",
           "meditateTag": "[592658589080879104]",
           "meditateCover": "https://oss-xingyun-platform.xypsy.com//886/2024/12/31/cfce81c1ebac4d9e93f3b3e76cb56cbc.jpg",
           "meditateDuration": 8,
           "meditatePosture": "坐姿",
           "meditateUseInstructions": "<p><span style=\"text-wrap-mode: nowrap;\">&nbsp; &nbsp;&nbsp;</span></p><p>&nbsp; &nbsp; &nbsp; 在这里的引导之下，你的每一次呼吸都能把疲惫慢慢放下，让情绪从压力中逃脱，回到学习的节奏中充满热情奋斗。学习的压力，它能够被看见与理解，从而被得以消解；呼吸的节奏，它牵动着思维的清晰度，通过调整便可能豁然开朗。在学业压力下，来给自己一些温柔的支持呀！</p><p><br/></p><p>&nbsp; &nbsp; &nbsp; 我们会带领你把注意力放回到自己到身体。呼吸，放松，重新出发，每一步都不急躁。</p><p><br/></p><p><br/></p><p><br/></p><p><span style=\"text-wrap-mode: nowrap;\"></span><br/></p>",
           "tag": []
         */
    }
}
